﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Overby
{
    [Serializable]
    public class SortExpression
    {
        public string Field { get; set; }
        public bool Descending { get; set; }

        public override string ToString()
        {
            return string.Format("{0} {1}", Field, Descending ? "DESC" : "ASC");
        }

        public override int GetHashCode()
        {
            return ToString().GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return obj != null
                && obj is SortExpression
                && ToString() == obj.ToString();
        }

        public static SortExpression Parse(string expression)
        {
            Action cantParse = () => { throw new FormatException("The expression cannot be parsed. Valid examples: \"Id: ascending\" or \"Age DESC\" or \"LastName.asc\" or \"EmailAddress\" "); };

            if (String.IsNullOrEmpty(expression))
                cantParse.Invoke();           

            var parts = expression.Split(@" ,./<>?;:'""[]\{}|!@#$%^&*()_+-=`~".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length < 1 || parts.Length > 2)
                cantParse.Invoke();

            SortExpression sortExpression = new SortExpression { Field = parts[0] };

            if (parts.Length == 2)
            {
                string direction = parts[1].ToLower();

                if (direction.StartsWith("a"))
                    sortExpression.Descending = false;
                else if (direction.StartsWith("d"))
                    sortExpression.Descending = true;
                else
                    cantParse.Invoke();
            }

            return sortExpression;
        }
    }
}